package com.lzx.adx.report.controller.v1.toutiao;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.HhTtEnum;
import com.lzx.adx.report.enums.TaoBaoCovertToutiaoEnums;
import com.lzx.adx.report.model.toutiao.request.TouTiaoRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import com.lzx.adx.report.util.UrlUtil;
import com.lzx.adx.report.util.helper.TouTiaoHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品：闲鱼
 * 媒体：今日头条
 */
@RequestMapping("/tt/xy")
@RestController
@Slf4j
public class TouTiaoXianYuController {

    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;

    @GetMapping("/report")
    public ResponseEntity report(TouTiaoRequest touTiaoRequest, HttpServletRequest request) {
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(touTiaoRequest.getDspId());
        log.info("接收到今日头条到{}的请求参数为{}", accountDTO.getName(), JsonUtils.toJsonString(touTiaoRequest));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(touTiaoRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(touTiaoRequest));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        String resultUrl = UrlUtil.covertHHUrl(accountDTO, reportDTO);
        log.info("账号{}头条闲鱼请求完整的url为{}", reportDTO.getDspId(), resultUrl);
        String result = HttpUtil.get(resultUrl);
        log.info("账号{}头条闲鱼请求响应结果为{}", reportDTO.getDspId(), result);
        return ResponseEntity.ok(new Result());
    }


    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId, String event_type) throws Exception {
        log.info("头条收到了闲鱼回调信息请求流水号{},回调类型为{}", requestId, event_type);
        if (StringUtils.isBlank(requestId)) {
            log.error("头条收到了闲鱼回调信息请求流水号空");
            return ResponseEntity.ok(new Result());
        }
        if (StringUtils.isBlank(event_type)) {
            log.info("请求流水号{},头条收到了闲鱼回调信息，回调类型为空，不做回传", requestId);
            return ResponseEntity.ok(new Result());
        }
        if (!"1".equals(event_type)) {
            log.info("请求流水号{},头条收到了闲鱼回调信息，回调类型为{}，不是注册，不做回传", requestId, event_type);
            return ResponseEntity.ok(new Result());
        }
        String event_time = String.valueOf(System.currentTimeMillis());
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(event_type);
            reportDTO.setResultTime(event_time);
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,event_type);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.从缓存加载配置
        String url = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        String resultUrl = url + "&event_type=active_register";
        log.info("账户:{},请求id:{}闲鱼-头条，请求完整的url为{}", reportDTO.getDspId(), requestId, resultUrl);
        String result = HttpUtil.get(resultUrl);
        log.info("账户:{},请求id:{}闲鱼-头条，响应结果为{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }


    @GetMapping("/yt/callback")
    public ResponseEntity ytCallBackUrl(String requestId, String event_type) throws Exception {
        log.info("头条收到了一淘(辉煌明天)回调信息请求流水号{},回调类型为{}", requestId, event_type);
        if (StringUtils.isBlank(requestId)) {
            log.error("头条收到了一淘(辉煌明天)回调信息请求流水号空");
            return ResponseEntity.ok(new Result());
        }
        if (StringUtils.isBlank(event_type)) {
            log.info("请求流水号{},头条收到了一淘(辉煌明天)回调信息，回调类型为空，不做回传", requestId);
            return ResponseEntity.ok(new Result());
        }
        String ttCode = HhTtEnum.getTtCode(event_type);
        if (null == ttCode) {
            log.info("请求流水号{},头条收到了一淘(辉煌明天)回调信息，回调类型为{}，不是注册，不做回传", requestId, event_type);
            return ResponseEntity.ok(new Result());
        }
        if ("active_register".equals(ttCode) || "next_day_open".equals(ttCode)) {
            log.info("请求流水号{},头条收到了一淘(辉煌明天)回调信息，回调类型异常，不做回传", requestId);
            return ResponseEntity.ok(new Result());
        }
        String event_time = String.valueOf(System.currentTimeMillis());
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(event_type);
            reportDTO.setResultTime(event_time);
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,event_type);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.从缓存加载配置
        String url = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        String resultUrl = url + "&event_type=active_register";
        log.info("账户:{},请求id:{}一淘-头条，请求完整的url为{}", reportDTO.getDspId(), requestId, resultUrl);
        String result = HttpUtil.get(resultUrl);
        log.info("账户:{},请求id:{}一淘-头条，响应结果为{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }


    @GetMapping("/yk/callback")
    public ResponseEntity ykCallBackUrl(String requestId, String event_type) throws Exception {
        log.info("头条收到了优酷(辉煌明天)回调信息请求流水号{},回调类型为{}", requestId, event_type);
        if (StringUtils.isBlank(requestId)) {
            log.error("头条收到了优酷(辉煌明天)回调信息请求流水号空");
            return ResponseEntity.ok(new Result());
        }
        if (StringUtils.isBlank(event_type)) {
            log.info("请求流水号{},头条收到了优酷(辉煌明天)回调信息，回调类型为空，不做回传", requestId);
            return ResponseEntity.ok(new Result());
        }
        String ttCode = HhTtEnum.getTtCode(event_type);
        if (null == ttCode) {
            log.info("请求流水号{},头条收到了优酷(辉煌明天)回调信息，回调类型为{}，不是注册，不做回传", requestId, event_type);
            return ResponseEntity.ok(new Result());
        }
        if ("active_register".equals(ttCode) || "next_day_open".equals(ttCode)) {
            log.info("请求流水号{},头条收到了一淘(辉煌明天)回调信息，回调类型异常，不做回传", requestId);
            return ResponseEntity.ok(new Result());
        }
        String event_time = String.valueOf(System.currentTimeMillis());
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(event_type);
            reportDTO.setResultTime(event_time);
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,event_type);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.从缓存加载配置
        String url = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        String resultUrl = url + "&event_type=active_register";
        log.info("账户:{},请求id:{}优酷-头条，请求完整的url为{}", reportDTO.getDspId(), requestId, resultUrl);
        String result = HttpUtil.get(resultUrl);
        log.info("账户:{},请求id:{}优酷-头条，响应结果为{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }


}
